package com.huilian.iotbox.admin.wap.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huilian.iotbox.admin.wap.config.DelayMQConfig;
import com.huilian.iotbox.admin.wap.service.RabbitSenderService;
import com.huilian.iotbox.data.config.MQConfig;
import com.huilian.iotbox.data.dto.DiscountPackageDto;
import com.huilian.iotbox.data.dto.LabelDto;
import com.huilian.iotbox.data.dto.MemberDto;
import com.huilian.iotbox.data.vo.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 谢洛涛
 * @date 2021/1/9 18:13
 */
@Service
@Slf4j
public class RabbitSenderServiceImpl implements RabbitSenderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendReplayMerchantSubmitRemoveInfoLazyQueue(String key, int delayTime) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        //全局唯一
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        //发送消息时指定并指定header延迟时间
        rabbitTemplate.convertAndSend(DelayMQConfig.IOT_BOX_WAP_LAZY_EXCHANGE, DelayMQConfig.IOT_BOX_WAP_MERCHANT_SUBMIT_REMOVE_INFO_LAZY_QUEUE_KEY, key,
                msg -> {
                    //设置消息持久化
                    msg.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    msg.getMessageProperties().setDelay(delayTime);
                    return msg;
                }, correlationData);
    }


    /**
     * 游戏币套餐变更（新增、排序、删除、修改）发mqtt通知设备，
     *
     * @param discountPackage
     */
    @Override
    public void sendDiscountPackageChange(DiscountPackageDto discountPackage) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("iotBox-discountPackage-change", "iotBox-discountPackage-change.iotBoxPayDiscountPackageChange", discountPackage, correlationData);
        log.info("--------发送MQ成功！--------时间{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    @Override
    public void sendReplayMemberDistributionCurrency(MemberDto memberDto) {
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("iotBox-memberDistributionCurrency-change", "iotBox-memberDistributionCurrency-change.iotBoxPayMemberDistributionCurrency",
                memberDto, correlationData);
        log.info("--------发送MQ成功！--------时间{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    //定义消息声明
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            String outTradeNo = correlationData.getId();
            if (!ack) {
                log.error("订单：{},发送失败", correlationData.getId());
                log.error("MQ订单发送失败，Confirm插入数据库");
            }
            log.info("RabbitMQ correlationDataID：{}MQ 发送成功！", outTradeNo);
        }
    };

    //定义消息返回
    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode,
                                    String replyTest, String exchange, String routingKey) {
            System.err.println("return: " + exchange + ",routingKey:" + routingKey + ",replyCode: " + replyCode + ",replyTest:" + replyTest);
            log.error("订单：{},发送失败", message);
            log.error("MQ订单发送失败，Confirm插入数据库");
        }
    };


}
